package b3.scene.home.grid
{
	import as3isolib.display.*;
	import as3isolib.geom.*;
	
	import b3.config.*;
	import b3.model.*;
	import b3.net.*;
	import b3.scene.home.*;
	import b3.widget.*;
	import b3.widget.basic.*;
	import b3.widget.home.operation.*;
	import b3.widget.home.town.*;
	
	import com.greensock.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.Point;
	import flash.text.*;
	import flash.utils.*;
	
	public class BuildingGrid extends IsoSprite
	{
		public var buildingModel:BuildingModel;
		private var buildingSprite:IsoSprite;
		private var collectRentBarSprite:IsoSprite;
		private var protectIconSprite:IsoSprite;
		private var sealIconSprite:IsoSprite;
		private var rentBubbleSprite:IsoSprite;
		private var socialBubbleSprite:IsoSprite;
		private var arrowSprite:IsoSprite;
		private var rentCountDownPane:RentCountDownPane;
		private var timer:Timer;
		private var shineFlag:Boolean;
		
		public function BuildingGrid(buildingModel:BuildingModel)
		{
			super();
			this.buildingModel = buildingModel;
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingModel.buildingIndex];
            var IsoImage:Class = ResourceHelper.getInstance().getClassByName(buildingConfig.isoImage[buildingModel.roofType + 1]);
            var isoImage:Sprite = new IsoImage();
            isoImage.cacheAsBitmap = true;
			setSize(Town.gridWidth, Town.gridWidth, Town.gridWidth);
			
			buildingSprite = new IsoSprite();
			buildingSprite.setSize(8, 8, 8);
			buildingSprite.sprites = [isoImage];
			addChild(buildingSprite);
            buildingSprite.container.mouseChildren = false;
          
			buildingSprite.container.addEventListener(MouseEvent.CLICK, onMouseClick);
			buildingSprite.container.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			buildingSprite.container.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			buildingSprite.container.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			buildingSprite.container.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			buildingSprite.container.addEventListener(Event.ADDED_TO_STAGE, onAddToStage);
			buildingSprite.container.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			buildingModel.addEventListener(ModelEvent.COLLECT_RENT_COMPLETE, onCollectRentComplete, false, 0, true);
		}
		
		public function onRefresh(event:ModelEvent):void
		{
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingModel.buildingIndex];
            var IsoImage:Class = ResourceHelper.getInstance().getClassByName(buildingConfig.isoImage[buildingModel.roofType + 1]);
            buildingSprite.sprites = [IsoImage];
            if (event.data != null)
            {
            	var socialType:int = event.data["socialType"];
            	var screenPos:Point = this.container.parent.localToGlobal(new Point(this.container.x, this.container.y));
            	//协助
            	if (socialType == SocialModel.ASSIST_REBUILD)
            	{
					//获得光明值动画
					HomeScene.getInstance().playerPane.lightPane.playAddMovie(screenPos, event.data['obj']['objectNum']);
            	}
            	//攻击
            	else if (socialType == SocialModel.ATTACK)
            	{
					//获得黑暗值动画
					HomeScene.getInstance().playerPane.darkPane.playAddMovie(screenPos, event.data['obj']['objectNum']);
					var occupyBuilding:Boolean = event.data["occupyBuilding"];
					var occupyTown:Boolean = event.data["occupyTown"];
					var me:Player = PlayerManager.getInstance().me;
					if (occupyTown)
					{
						//弹出提示
						var popMessage:PopMessage = new PopMessage("成功占领城市！");
						WidgetManager.getInstance().popOut([popMessage]);
						//检查任务
						me.taskList.finishTask(TaskConfig.ID_OCCUPY_TOWN);
						//更新占领者
						HomeScene.getInstance().occupantPane.setOccupant(me.userId);
					}
					else if (occupyBuilding)
					{
						//弹出提示
						popMessage = new PopMessage("成功占领建筑！你成为了房东！");
						WidgetManager.getInstance().popOut([popMessage]);
						//检查任务
						me.taskList.finishTask(TaskConfig.ID_OCCUPY_BUILDING);
					}
            	}
            	//恶魔卡
            	else if (socialType == CardConfig.DEVIL_SMALL || socialType == CardConfig.DEVIL_BIG)
            	{
            		playDevilCardEffect();
            	}
            	//天使卡
            	else if (socialType == CardConfig.ANGEL_SMALL || socialType == CardConfig.ANGEL_BIG)
            	{
            		playAngelCardEffect();
            	}
            }
		}

		virtual protected function onMouseClick(event:MouseEvent):void
		{
			stopShine();
			hideArrow();
			var home:HomeScene = HomeScene.getInstance();
			var me:Player = PlayerManager.getInstance().me;
			if (buildingModel.locatedFlag && home.getOperationMode() == HomeScene.NONEMODE)
			{
				//已经被查封
				if (buildingModel.remainTimeToStopSeal() > 0)
				{
					//只能查看信息
					var operationPane:OperationPane = new OperationPane(buildingModel);
					operationPane.effect = BasicWidget.EFFECT_EXPAND;
					var screenPos:Point = this.mainContainer.parent.localToGlobal(new Point(this.mainContainer.x, this.mainContainer.y));
					operationPane.x = screenPos.x - operationPane.width / 2;
					operationPane.y = screenPos.y - operationPane.height / 2 - buildingSprite.container.height / 2;
					operationPane.addOperation(OperationPane.INFO,    OperationPane.LEFT);
					WidgetManager.getInstance().popOut([operationPane]);
					//弹出信息
					var popMessage:PopMessage = new PopMessage("该楼已被查封！", 0xFF0000);
					WidgetManager.getInstance().popOut([popMessage]);
				}
				//可以收租
				else if (buildingModel.isReadyToCollectRent())
				{
					startCollectRent();
				}
				else
				{
					//非中立城市
					if (home.getCurrentTown().owner.type != PlayerManager.CENTER_TYPE)
					{
						operationPane = new OperationPane(buildingModel);
						operationPane.effect = BasicWidget.EFFECT_EXPAND;
						screenPos = this.mainContainer.parent.localToGlobal(new Point(this.mainContainer.x, this.mainContainer.y));
						operationPane.x = screenPos.x - operationPane.width / 2;
						operationPane.y = screenPos.y - operationPane.height / 2 - buildingSprite.container.height / 2;
						//如果在自家且占领者是自己
						if (buildingModel.ownerId == me.userId && buildingModel.occupantId == me.userId)
						{
							operationPane.addOperation(OperationPane.REMOVE,  OperationPane.TOP);
							operationPane.addOperation(OperationPane.REBUILD, OperationPane.BOTTOM);
							operationPane.addOperation(OperationPane.INFO,    OperationPane.LEFT);
						}
						//如果在自家但占领者不是自己
						else if (buildingModel.ownerId == me.userId && buildingModel.occupantId != me.userId)
						{
							operationPane.addOperation(OperationPane.ATTACK, OperationPane.TOP);
							operationPane.addOperation(OperationPane.ASSIST, OperationPane.BOTTOM);
							operationPane.addOperation(OperationPane.INFO,    OperationPane.LEFT);
						}
						//如果不在自家但占领者是自己
						else if (buildingModel.ownerId != me.userId && buildingModel.occupantId == me.userId)
						{
							operationPane.addOperation(OperationPane.ASSIST, OperationPane.BOTTOM);
							operationPane.addOperation(OperationPane.INFO,   OperationPane.TOP);
						}
						//如果在别人家且占领者不是自己
						else
						{
							operationPane.addOperation(OperationPane.ATTACK, OperationPane.TOP);
							operationPane.addOperation(OperationPane.ASSIST, OperationPane.BOTTOM);
							operationPane.addOperation(OperationPane.INFO,   OperationPane.LEFT);
						}
						WidgetManager.getInstance().popOut([operationPane]);
					}
				}
			}
			//点击卡片
			else if (home.getOperationMode() == HomeScene.USECARDMODE)
			{
				//中立城市
				if (home.getCurrentTown().owner.type == PlayerManager.CENTER_TYPE)
				{
					
				}
				else
				{
					//获取 卡片使用对象
					home.cardItem.cardModel.setTarget(buildingModel);
				}
			}
		}
		
		//收租
		private function startCollectRent():void
		{
			//暂停租金的定时检查
			stopTimer();
			if (collectRentBarSprite == null)
			{
				//进度条
				var RentProgressBarFrame:Class = ResourceHelper.getInstance().getClassByName("RentProgressBarFrame");
				var RentProgressBar:Class = ResourceHelper.getInstance().getClassByName("RentProgressBar");
				var progressBar:ProgressBar = new ProgressBar(RentProgressBarFrame, RentProgressBar, 0);
				collectRentBarSprite = new IsoSprite();
				collectRentBarSprite.setSize(8, 8, 8);
				collectRentBarSprite.sprites = [progressBar];
				collectRentBarSprite.moveTo(0, 50, height + 20);
				addChild(collectRentBarSprite);
				TweenLite.to(progressBar, 2, {percentage: 1, onComplete:onCollectRentBarComplete});
			} 
		}
		
		//收租进度条完成
		private function onCollectRentBarComplete():void
		{
			if (collectRentBarSprite != null)
				removeChild(collectRentBarSprite);
			if (rentBubbleSprite != null)
				removeChild(rentBubbleSprite);
			collectRentBarSprite = null;
			rentBubbleSprite = null;
			if (buildingModel != null)
				buildingModel.collectRent(true);
		}
		
		//收租完成
		private function onCollectRentComplete(event:ModelEvent):void
		{
			//重启租金的定时检查
			startTimer();
			var data:Object = event.data;
			//成功收租
			if (data["err"] == 0)
			{
				var rentObjectIndex:int = data['rentObjectIndex']; 
				//收租成功动画
				var screenPos:Point = this.container.parent.localToGlobal(new Point(this.container.x, this.container.y));
				if (rentObjectIndex == ObjConfig.GOLDCOIN)
				{
					HomeScene.getInstance().goldCoinPane.playAddMovie(screenPos, data['obj']['objectNum']);
				}
				else if (rentObjectIndex == ObjConfig.NATIONAL_STAR)
				{
					HomeScene.getInstance().nationalStarPane.playAddMovie(screenPos, data['obj']['objectNum']);
				}
			}
			else
			{	
				var popMessage:PopMessage;
				if (data["err"] == 100)
				{
					popMessage = new PopMessage("尚未到收租时间", 0xFF0000);
				}
				else if (data["err"] == 101)
				{
					popMessage = new PopMessage("此楼已经被偷得所剩无几", 0xFF0000);
				}
				else if (data["err"] == 102)
				{
					popMessage = new PopMessage("今天已经偷过这栋楼", 0xFF0000);
				}
				else if (data["err"] == 103)
				{
					popMessage = new PopMessage("该楼已不存在", 0xFF0000);
				}
				else if (data["err"] == 104)
				{
					popMessage = new PopMessage("今儿偷他不少次，明儿再来", 0xFF0000);
				}
				else if (data['err'] == 815)
				{
					popMessage = new PopMessage("本楼已被查封", 0xFF0000);
				}
				else
				{
					popMessage = new PopMessage("其他错误:", data["err"]);
				}
				WidgetManager.getInstance().popOut([popMessage]);
			}
		}
	
		private function onAddToStage(event:Event):void
		{
			startTimer();
			//自己家并且有新的社交信息
			if (buildingModel.ownerId == PlayerManager.getInstance().myUserId)
			{
				if (!buildingModel.socialMessageRead)
				{
					showSocialBubble();
				}
			}
			if (shineFlag)
				this.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true);
		}
		
		private function onRemovedFromStage(event:Event):void
		{
			stopTimer();
			if (shineFlag)
				this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function startTimer():void
		{
			if (this.parent != null && buildingModel.locatedFlag)
			{
				timer = new Timer(1000);
				timer.addEventListener(TimerEvent.TIMER, onTick);
				timer.start();
			}
		}
		
		private function stopTimer():void
		{
			if (timer != null)
			{
				timer.removeEventListener(TimerEvent.TIMER, onTick);
				timer.stop();
			}
			timer = null;
		}
		
		private function onTick(event:Event):void
		{
			var timeToStopProtect:int = buildingModel.remainTimeToStopProtect(); 
			//是否保护
			if (timeToStopProtect > 0)
			{
				showProtectIcon();
			}
			//已经被查封
			var timeToStopSeal:int = buildingModel.remainTimeToStopSeal(); 
			if (timeToStopSeal > 0)
			{
				showSealIcon();
				if (rentCountDownPane != null)
					rentCountDownPane.updateRemainTime(timeToStopSeal, " 后解封");
			}
			//可以收租
			else if (buildingModel.isReadyToCollectRent())
			{
				showRentBubble();
				if (timeToStopProtect > 0)
				{
					if (rentCountDownPane != null)
						rentCountDownPane.updateRemainTime(timeToStopProtect, " 后保护消失");
				}
			}
			else
			{
				if (rentCountDownPane != null)
					rentCountDownPane.updateRemainTime(buildingModel.remainTimeToCollectRent(), " 后收租");
			}
		}
		
		//播放恶魔卡效果
		private function playDevilCardEffect():void
		{
			var cardConfig:CardConfig = Config.objConfigs[319];
			var DevilImg:Class = ResourceHelper.getInstance().getClassByName(cardConfig.iconImage[0]);
			var devilImg:Sprite = new DevilImg();
			devilImg.width = 50;
			devilImg.scaleY = devilImg.scaleX;
			var devilSprite:IsoSprite = new IsoSprite();
			devilSprite.setSize(8, 8, 8);
			devilSprite.sprites = [devilImg];
			devilSprite.moveTo(width / 2 - 50, 0, height + 20);
			addChild(devilSprite);
			var timeline:TimelineLite = new TimelineLite();
			timeline.append(new TweenLite(devilSprite, 0.4, {z: height}));
			timeline.append(new TweenLite(devilSprite, 0.2, {z: height + 20}));
			timeline.append(new TweenLite(devilSprite, 0.4, {z: height}));
			timeline.append(new TweenLite(devilSprite, 0.2, {z: height + 20}));
			timeline.append(new TweenLite(devilSprite, 0.4, {z: height, onComplete: removeChild, onCompleteParams: [devilSprite]}));
		}
		
		//播放天使卡效果
		private function playAngelCardEffect():void
		{
			var cardConfig:CardConfig = Config.objConfigs[317];
			var DevilImg:Class = ResourceHelper.getInstance().getClassByName(cardConfig.iconImage[0]);
			var devilImg:Sprite = new DevilImg();
			devilImg.width = 50;
			devilImg.scaleY = devilImg.scaleX;
			var SunShine:Class = ResourceHelper.getInstance().getClassByName("SunShine");
			var sunShine:Sprite = new SunShine();
			sunShine.x = -160;
			sunShine.y = -180;
			var devilSprite:IsoSprite = new IsoSprite();
			devilSprite.setSize(8, 8, 8);
			devilSprite.sprites = [sunShine, devilImg];
			devilSprite.moveTo(width / 2 - 50, 0, height - 10);
			addChild(devilSprite);
			var timeline:TimelineLite = new TimelineLite();
			timeline.append(new TweenLite(devilSprite, 0.8, {z: height + 70}));
			timeline.append(new TweenLite(devilSprite.container, 0.8, {alpha: 0, onComplete: removeChild, onCompleteParams: [devilSprite]}));
		}
		
		//显示保护图标
		private function showProtectIcon():void
		{
			if (protectIconSprite == null)
			{
				var stateConfig:StateConfig = Config.stateConfigs[821];
				var ProtectIcon:Class = ResourceHelper.getInstance().getClassByName(stateConfig.iconImage[0]);
				var smallBubble:Sprite = new ProtectIcon();
				smallBubble.width = 40;
				smallBubble.scaleY = smallBubble.scaleX;
				smallBubble.x = -smallBubble.width / 2;
				smallBubble.y = -132;
				
				protectIconSprite = new IsoSprite();
				protectIconSprite.setSize(8, 8, 8);
				protectIconSprite.sprites = [smallBubble];
				addChild(protectIconSprite);
			}
		}
		
		//显示查封图标
		private function showSealIcon():void
		{
			if (sealIconSprite == null)
			{
				var stateConfig:StateConfig = Config.stateConfigs[815];
				var SealIcon:Class = ResourceHelper.getInstance().getClassByName(stateConfig.iconImage[0]);
				var smallBubble:Sprite = new SealIcon();
				smallBubble.width = 40;
				smallBubble.scaleY = smallBubble.scaleX;
				smallBubble.x = -smallBubble.width / 2;
				smallBubble.y = -90;
				
				sealIconSprite = new IsoSprite();
				sealIconSprite.setSize(8, 8, 8);
				sealIconSprite.sprites = [smallBubble];
				addChild(sealIconSprite);
			}
		}
		
		//开始闪烁
		public function startShine():void
		{
			if (!shineFlag)
			{
				this.shineFlag = true;
				this.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true);
			}
		}
		
		//停止闪烁
		public function stopShine():void
		{
			if (shineFlag)
			{
				this.shineFlag = false;
				buildingSprite.container.filters = null;
				this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			}
		}
		
		private function onEnterFrame(event:Event):void
		{
			var shineFilterAlpha:Number = Math.sin(getTimer() / 150);
			var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
			gradientGlow.distance = 0;
			gradientGlow.angle = 45;
			gradientGlow.colors = [0xFFFF00, 0xFFFF00];
			gradientGlow.alphas = [0, shineFilterAlpha];
			gradientGlow.ratios = [0, 255];
			gradientGlow.blurX = 15;
			gradientGlow.blurY = 15;
			gradientGlow.strength = 3;
			gradientGlow.quality = BitmapFilterQuality.HIGH;
			gradientGlow.type = BitmapFilterType.OUTER;
			buildingSprite.container.filters = [gradientGlow];
		}
		
		//显示箭头
		public function showArrow():void
		{
			if (arrowSprite == null)
			{
				var ArrowImg:Class = ResourceHelper.getInstance().getClassByName("NewHelperArrow");
				var arrowImg:Sprite = new ArrowImg();
				arrowImg.x = -arrowImg.width / 2;
				arrowSprite = new IsoSprite();
				arrowSprite.setSize(8, 8, 8);
				arrowSprite.sprites = [arrowImg];
				arrowSprite.moveTo(width / 2, 0, height + 150);
				addChild(arrowSprite);
			}
		}
		
		//隐藏箭头
		public function hideArrow():void
		{
			if (arrowSprite != null)
			{
				removeChild(arrowSprite);
				arrowSprite = null;
			}
		}
		
		//显示社交气泡
		private function showSocialBubble():void
		{
			if (socialBubbleSprite == null)
			{
				var SocialDialogBgr:Class = ResourceHelper.getInstance().getClassByName("SocialDialogBgr");
				var smallBubble:Sprite = new SocialDialogBgr();
				smallBubble.width = 50;
				smallBubble.scaleY = smallBubble.scaleX;
				
				socialBubbleSprite = new IsoSprite();
				socialBubbleSprite.setSize(8, 8, 8);
				socialBubbleSprite.sprites = [smallBubble];
				socialBubbleSprite.moveTo(width / 2, 0, height + 20);
				addChild(socialBubbleSprite);
			}
		}
		
		//显示收租气泡
		private function showRentBubble():void
		{
			if (rentBubbleSprite == null)
			{
				var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingModel.buildingIndex];
				var objectConfig:ObjConfig = Config.objConfigs[buildingConfig.rentObjectIndex];
				var GoldCoinIcon:Class = ResourceHelper.getInstance().getClassByName(objectConfig.iconImage[0]);
				var smallBubble:Sprite = new GoldCoinIcon();
				smallBubble.width = 40;
				smallBubble.scaleY = smallBubble.scaleX;
				smallBubble.x = -smallBubble.width / 2;
				smallBubble.y = -90;
				
				rentBubbleSprite = new IsoSprite();
				rentBubbleSprite.setSize(8, 8, 8);
				rentBubbleSprite.sprites = [smallBubble];
				addChild(rentBubbleSprite);
			}
		}
		
		private function showSocialInfo(event:MouseEvent):void
		{
			var dialog:SocialDialog = new SocialDialog(buildingModel);
			var screenPos:Point = this.mainContainer.parent.localToGlobal(new Point(this.mainContainer.x, this.mainContainer.y));
			dialog.x = screenPos.x + this.container.width / 2;
			dialog.y = screenPos.y - dialog.height / 2 - this.container.height / 2;
			WidgetManager.getInstance().popOut([dialog]);
		}
		
		//显示倒计时		
		private function showCountDownPane(remainTime:int, text:String):void
		{
			if (rentCountDownPane == null)
				rentCountDownPane = new RentCountDownPane();
			rentCountDownPane.updateRemainTime(remainTime, text);
			var screenPos:Point = this.container.parent.localToGlobal(new Point(this.container.x, this.container.y));
			rentCountDownPane.x = screenPos.x - rentCountDownPane.width / 2;
			rentCountDownPane.y = screenPos.y - rentCountDownPane.height / 2 - this.container.height / 2 - 28;
			WidgetManager.getInstance().popOut([rentCountDownPane]);
		}
		
		private function hideCountDownPane():void
		{
			if (rentCountDownPane != null)
				rentCountDownPane.close();
			rentCountDownPane = null;	
		}
		
		private function onMouseDown(event:MouseEvent):void
		{
			container.alpha = 0.4;
		}    
		
		private function onMouseUp(event:MouseEvent):void
		{
			container.alpha = 1;
		} 

		private function onMouseOver(event:MouseEvent):void
		{
			var currentMode:int = HomeScene.getInstance().getOperationMode();
			if (currentMode == HomeScene.NONEMODE ||  currentMode == HomeScene.USECARDMODE)
			{
				buildingSprite.container.filters = [new GlowFilter(0x00FFFF, 1, 2.5, 2.5, 100, BitmapFilterQuality.HIGH)];
				//弹出提示窗口
				popInfo();
				//显示街区人口
				HomeScene.getInstance().centerInfoPane.showInfo(getSectionInfo(buildingModel.sectionIndex));
				//显示收租倒计时
				if (buildingModel.occupantId == PlayerManager.getInstance().myUserId)
				{
					var remainTimeToStopSeal:int = buildingModel.remainTimeToStopSeal();
					if (remainTimeToStopSeal > 0)
					{
						showCountDownPane(remainTimeToStopSeal, " 后解封");
					}
					else
					{
						var remainTimeToCollectRent:int = buildingModel.remainTimeToCollectRent();
						if (remainTimeToCollectRent > 0)
						{
							showCountDownPane(remainTimeToCollectRent, " 后收租");
						}
						else
						{
							var remainTimeToStopProtect:int = buildingModel.remainTimeToStopProtect();
							if (remainTimeToStopProtect > 0)
							{
								showCountDownPane(remainTimeToStopProtect, " 后保护消失");
							}
						}
					}
				}
			}
		}
		
		//获得街区信息
		private function getSectionInfo(sectionIndex:int):Sprite
		{
			var container:Sprite = new Sprite();		
			//图标
			var IconImage:Class = ResourceHelper.getInstance().getClassByName("SectionIcon" + sectionIndex);
			var iconImage:Sprite = new IconImage();
			iconImage.height = 50;
			iconImage.scaleX = iconImage.scaleY;
			container.addChild(iconImage);
			var PopulationIcon:Class = ResourceHelper.getInstance().getClassByName("PopulationIcon");
			var populationIcon:Sprite = new PopulationIcon();
			populationIcon.height = 40;
			populationIcon.scaleX = populationIcon.scaleY;
			populationIcon.x = 50;
			populationIcon.y = 10;
			container.addChild(populationIcon);
			//人口
			var owner:Player = PlayerManager.getInstance().players[buildingModel.ownerId];
			var populationText:TextField = new TextField();
			populationText.selectable = false;
			populationText.autoSize = TextFieldAutoSize.LEFT;
			populationText.defaultTextFormat = new TextFormat("微软雅黑", 25, 0xFFFFFF, true);
			populationText.filters = [new GlowFilter(0x00AAFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			populationText.text = owner.packageModel.getObjectNum(ObjConfig.SECTION_POPULATION + sectionIndex).toString();
			populationText.x = 85;
			populationText.y = 12;
			container.addChild(populationText);
			return container;
		}

		/**
		 * 独立的弹窗代码
		 */
		private function popWidget(text:String):void
		{
			var buildingInfoPane:BuildingInfoPane = new BuildingInfoPane(text);
			var screenPos:Point = this.mainContainer.parent.localToGlobal(new Point(this.mainContainer.x, this.mainContainer.y));
			buildingInfoPane.x = screenPos.x - buildingInfoPane.width / 2;
			buildingInfoPane.y = screenPos.y - buildingInfoPane.height / 2 - this.mainContainer.height / 2;
			WidgetManager.getInstance().popOutSeveralMessages(buildingInfoPane);
		}
		
		/**
		 * makeInfo函数生成提示信息  该提示信息出现在用户鼠标滑过建筑物上方时
		 */
		private function popInfo():void
		{
			var text:String ="";
			//显示自身信息时必然是重新显示 因此需要关闭其他
			WidgetManager.getInstance().closeSeveralMessages();
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingModel.buildingIndex];
			//如果建筑本身是绿化建筑
			if (buildingConfig.type == BuildingConfig.GREEN)
			{
				text = "+" + (buildingModel.population / 10).toString() + "%";
				//应该同时通知周围建筑显示本绿化建筑的正面影响
				var town:Town = HomeScene.getInstance().getCurrentTown();
				
				//针对每个点都寻找周围的建筑
				const points:Object = { 1:{x:-1,y:0}, 2:{x:-1,y:-1}, 3:{x:-1,y: 1}, 4:{x:0,y:-1},
										 5:{x: 1,y:1}, 6:{x: 1,y: 0}, 7:{x: 1,y:-1}, 8:{x:0,y: 1} };
				for (var i:int = 1; i <= 8; i++)
				{
					var x:int = buildingModel.posX + points[i]["x"];
					var y:int = buildingModel.posY + points[i]["y"];
					var tempBuilding:BuildingGrid = town.getBuildingByPos(x,y);
					//通知相关建筑需要弹出提示信息
					if (tempBuilding!=null )
					{//
						
						tempBuilding.popGreenMessage(buildingModel);
					}
				}	
			}
			//如果是 普通建筑
			else
			{
//				var townModel:TownModel = HomeScene.getInstance().getCurrentTown().owner.townModel;
//				var greenNum:int = townModel.getNearGreenSumNum(buildingModel.posX, buildingModel.posY, buildingModel.isoWidth, buildingModel.isoHeight);
//				if (greenNum > 0)
//				{
//					text = buildingModel.population.toString() + "+" + Math.floor(buildingModel.population * greenNum / 1000).toString();
//				}
//				else
				{
					text = buildingModel.population + "/" + buildingModel.historyMaxPopulation;
				}
				
			}
			popWidget(text);
		}

		/**
		 * 如果是正在覆盖别人的建筑物 这里需要进行判断 判断是否对周围建筑产生了影响
		 * town 通过获得town的引用来使得对其它人的通知变成可能 
		 * replaceBuildings 记录下所有被覆盖的全部建筑物
		 */ 
		public function popCoverMessage(replaceBuildings:Array ):void
		{
			var town:Town = HomeScene.getInstance().getCurrentTown();
			var text:String = "";
			//显示覆盖信息时同样是重新 因此关闭其他
			WidgetManager.getInstance().closeSeveralMessages();
			var effectBuildings:Object = new Object();//设立一个受影响建筑列表
			var pts:Array = buildingModel.getPts();
			for (var m:int = 0; m < pts.length; m++)
			{
				//针对每个点都寻找周围的建筑
				var points:Object = { 1:{x:-1,y:0}, 2:{x:-1,y:-1}, 3:{x:-1,y: 1}, 4:{x:0,y:-1},
									  5:{x: 1,y:1}, 6:{x: 1,y: 0}, 7:{x: 1,y:-1}, 8:{x:0,y: 1} };
				//查看本建筑周围可能存在的建筑
				for (var i:int = 1;i <= 8;i++)
				{
					var x:int = (pts[m] as Point).x + points[i]["x"];
					var y:int = (pts[m] as Point).y + points[i]["y"];
					var tempBuilding:BuildingGrid = town.getBuildingByPos(x,y);
					if (tempBuilding != null)
					{	
						//通知相关建筑需要弹出提示信息
						effectBuildings[tempBuilding.buildingModel.posX+"_"+tempBuilding.buildingModel.posY] = tempBuilding;
					}
				}
			}
			//受影响的建筑必须没有被取代 这样才能在图上显示提示
			if (replaceBuildings != null)
			{
				for (i = 0; i < replaceBuildings.length; i++)
				{
					x = (replaceBuildings[i] as BuildingGrid).buildingModel.posX;
					y = (replaceBuildings[i] as BuildingGrid).buildingModel.posY;
					effectBuildings[x+"_"+y] = null;
				}
			}
			//通知受影响建筑显示信息
			for (var key:String in effectBuildings)
			{
				if (effectBuildings[key]!=null)
					(effectBuildings[key] as BuildingGrid).popGreenMessage(buildingModel,replaceBuildings);
			}
			
			var buildingConfig:BuildingConfig = Config.buildingConfigs[buildingModel.buildingIndex];
			var population:int = 0;
			if (buildingConfig.type != BuildingConfig.GREEN) population += buildingModel.population;//不是绿色建筑才需要有人口变动
			if (replaceBuildings != null)
			{
				for (i = 0; i < replaceBuildings.length;i++)
				{
					var replaceBuilding:BuildingGrid = replaceBuildings[i] as BuildingGrid;
					//如果被取代的建筑物不是绿色建筑
					if ((Config.buildingConfigs[replaceBuilding.buildingModel.buildingIndex] as BuildingConfig).type != BuildingConfig.GREEN)
					{
						population -= replaceBuilding.buildingModel.population;
					}
				}
			}
			text = (population > 0 ? "+" : "") + population;
			popWidget(text);
		}
		/**
		 * 这里是受到影响时需要生成的提示信息
		 * 这个函数需要进行的判断包括 被取代的建筑物是否为自己周围的绿色建筑物 并且计算人口损失并显示
		 * 取代别人的建筑物是否为自己周围的绿色建筑物 计算人口增加
		 * 如果周围没有绿色建筑变动 那么不显示任何信息
		 * 由以上结果显示最后信息
		 */
		 public function popGreenMessage(newBuildingModel:BuildingModel, replaceBuildings:Array = null):void
		 {
		 	var town:Town = HomeScene.getInstance().getCurrentTown();
		 	var buildingType:int = (Config.buildingConfigs[buildingModel.buildingIndex] as BuildingConfig).type;
		 	if ( buildingType == BuildingConfig.GREEN || buildingModel.id == 0) return;
		 	var text:String = null;
		 	var newBuild:BuildingModel = newBuildingModel;
		 	var greenNum:int = 0;
		 	var changeFlag:Boolean = false;
		 	
		 	if ((Config.buildingConfigs[newBuild.buildingIndex] as BuildingConfig).type == BuildingConfig.GREEN && isNearMe(newBuild))
		 	{
		 		//如果新建筑是绿化建筑 并且在本建筑的周围
		 		greenNum += newBuild.population;
		 		changeFlag = true;
		 	}
		 	if (replaceBuildings != null )
		 	{
		 		for (var i:int = 0; i < replaceBuildings.length;i++)
			 	{
			 		//遍历所有的被取代建筑
			 		var replaceBuilding:BuildingModel = (replaceBuildings[i] as BuildingGrid).buildingModel ;
			 		//如果被取代建筑包含绿色建筑
			 		if ((Config.buildingConfigs[replaceBuilding.buildingIndex] as BuildingConfig).type == BuildingConfig.GREEN && isNearMe(replaceBuilding))
			 		{		 			
			 			greenNum -= replaceBuilding.population;
			 			changeFlag = true;
			 		}
			 	}
		 	}
		 	if (changeFlag) 
		 		text = (greenNum>0?"+":"")+Math.floor(greenNum*buildingModel.population/1000).toString();
		 	//提示信息为非空 说明需要提示
		 	if (text != null)
		 		popWidget(text);
		 }
		 
		 private function isNearMe(otherBuilding:BuildingModel):Boolean
		 {
		 	//判断这个建筑与本建筑是否相邻
		 	var me:Array = buildingModel.getPts();
		 	var other:Array = otherBuilding.getPts();
		 	for (var i:int = 0;i < me.length;i++)
		 	{
		 		for (var j:int = 0;j<other.length;j++)
		 		{
		 			if (Math.abs((me[i] as Point).x - (other[j] as Point).x) <2 
		 			&& Math.abs((me[i] as Point).y - (other[j] as Point).y) <2)
					{
		 				return true;//只要在相邻的格子之内立即判定为相邻
		 			}
		 		}
		 	}
		 	return false;
		}
		
		private function onMouseOut(event:MouseEvent):void
		{
			buildingSprite.container.filters = null;
			buildingSprite.container.alpha = 1;
			hideCountDownPane();
			WidgetManager.getInstance().closeSeveralMessages();
			HomeScene.getInstance().centerInfoPane.clear();
		}
		
		public function destroy():void
		{
			stopTimer();
			container.removeEventListener(MouseEvent.CLICK, onMouseClick);
			container.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			container.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			container.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			container.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
			container.removeEventListener(Event.ADDED_TO_STAGE, onAddToStage);
			container.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			buildingModel.removeEventListener(ModelEvent.COLLECT_RENT_COMPLETE, onCollectRentComplete);
			buildingModel = null;
			if (rentCountDownPane != null)
				rentCountDownPane.close();
		} 
	}
}